package com.myk.game.lib.views;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

import java.util.Calendar;

public class WeekTextView extends AppCompatTextView {

    private static final String[] WEEK_DAYS = {
            "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"
    };
    private final WeekTextView textView;
    private final TimeHandler mTimeHandler = new TimeHandler();
    private String week;

    public WeekTextView(Context context) {
        this(context, null);
    }

    public WeekTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.textView = this;
        //++格式用属性控制
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        init();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mTimeHandler.stopScheduleUpdate();
    }

    private void init() {
        try {
            //初始化textview显示时间
            updateClock();
            //更新线程开始
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mTimeHandler.startScheduleUpdate();
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //更新Handler通过handler的延时发送消息来更新日期
    @SuppressLint("HandlerLeak")
    private class TimeHandler extends Handler {
        private boolean mStopped;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!mStopped) {
                updateClock();
                post();//实现实时更新
            }
        }

        //每隔1秒发送一次消息
        private void post() {
            sendMessageDelayed(obtainMessage(0), 1000);
        }

        //开始更新
        public void startScheduleUpdate() {
            mStopped = false;
            post();
        }

        //停止更新
        public void stopScheduleUpdate() {
            mStopped = true;
            removeMessages(0);
        }
    }

    //返回当前的日期
    public String getWeek() {
        return week;
    }

    //更新当前时日期
    private void updateClock() {
        Calendar calendar=Calendar.getInstance();
        week = WEEK_DAYS[calendar.get(Calendar.DAY_OF_WEEK)-1];
        textView.setText(week);
    }
}
